import { HttpClient } from '@angular/common/http'
import { Component, OnInit } from '@angular/core'
import { ErrorCollect } from 'src/app/service/app-http-inteceptor.provider'
import AppApi from '../../api/index'
import { NavState } from '../../common/const/nav-state.const'
import { AppJWTService } from '../../service/app-jwt.service'
import { AppMessageDialogService } from '../../service/app-message-dialog.service'
import { AppRouterService } from '../../service/app-router.service'
import { AppStateService } from '../../service/app-state.service'

@Component({
  selector: 'Login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
  private _username: string
  private _password: string

  isLoging = false

  constructor(
    private http: HttpClient,
    private appJwtService: AppJWTService,
    private appStateService: AppStateService,
    private appRouter: AppRouterService,
    private msgService: AppMessageDialogService,
  ) { }

  ngOnInit(): void {
    this.appJwtService.isAuthenticated().subscribe(
      next => {
        if (next) {
          this.appStateService.navState = NavState.NORMAL
          this.appRouter.navigate(['home'])
        }
        else {
          this.appStateService.navState = NavState.ANONYMOUS
          this.username = 'admin'
          this.password = 'admin'
        }
      }
    )
  }

  keydownHandle($event: KeyboardEvent): void {
    if ($event.keyCode === 13) this.doLogin() // enter keycode is  13
  }

  doLogin(): void {
    this.isLoging = true
    this.http.post<any>(AppApi.UserApi.login, {
      username: this.username,
      password: this.password
    }).subscribe(rsp => {
      this.appJwtService.updateAuthToken(rsp.token).subscribe(
        result => {
          this.appStateService.navState = NavState.NORMAL
          this.appRouter.navigate(['home'])
        },
        (error: ErrorCollect) => {
          this.msgService.showMessage(error.errTitle, error.errDetail)
        }
      )
    }, error => {
      this.msgService.showMessage('登录失败', error)
      this.isLoging = false
    }, () => this.isLoging = false)
  }

  public get username(): string {
    return this._username
  }
  public set username(value: string) {
    this._username = value
  }
  public get password(): string {
    return this._password
  }
  public set password(value: string) {
    this._password = value
  }

}
